const { serverUrl } = require("../../config/env");
const { addGoods, getCategoryList } = require("../../apis/goods");

// pages/manager/index.js
Page({
  /**
   * 页面的初始数据
   */
  data: {
    goodsName: "",
    goodsPrice: "",
    goodsImg: "",
    categoryId: null,
    categoryName: "",
    categoryList: [],
    categoryPopup: false,
    fileList: [],
  },

  bindPickerChange(event) {
    const { picker, value, index } = event.detail;
    console.log(value, index);

    this.setData({
      categoryId: value.id,
      categoryName: value.name,
    });
    this.setData({
      categoryPopup: false,
    });
  },
  onCancel() {
    this.setData({
      categoryPopup: false,
    });
  },
  showPopup() {
    this.setData({
      categoryPopup: true,
    });
  },
  async saveGoods() {
    const { goodsName, goodsPrice, goodsImg, categoryId } = this.data;
    if (!categoryId) return;
    const res = await addGoods({
      goodsName,
      goodsPrice,
      goodsImg,
      categoryId,
    });
  },
  async getCategory() {
    const res = await getCategoryList();
    this.setData({
      categoryList: res,
    });
  },

  handleAfterRead(event) {
    const { file } = event.detail;
    const that = this;
    // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
    wx.uploadFile({
      url: serverUrl + "/file/img", //仅为示例，非真实的接口地址
      filePath: file.url,
      name: "file",
      header: {
        token: wx.getStorageSync("token"),
      },
      formData: {
        path: "goods",
        isCompress: 1,
      },
      success(res) {
        console.log(res);
        if (res.data) {
          const obj = JSON.parse(res.data);
          if (obj.code === 0) {
            // 上传完成需要更新 fileList
            const { fileList = [] } = that.data;
            fileList.push({ ...file, url: file.url });
            that.setData({ fileList, goodsImg: obj.data });
          }
        }
      },
    });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.getCategory();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {},
});
